import VueRouter from "vue-router";
import pages from "../pages";
import layout from "./layout";
import store from './store';

const menus = [];
const pagesRouters = [];

Object.values(pages).forEach(p => {

    // 业务顶级菜单
    const menu = {
        name: p.name,
        path: `/${p.name}/`,
        title: p.title,
        children: [],
    };
    // 业务顶级路由
    const router = {
        ...menu,
        component: layout,
        children: (p.routers || []).map(v => {
            return {...v, name: p.name + '-' + v.name};
        }),
    };

    if (p.menus) {
        // 单独定义了菜单，使用菜单
        menu.children = p.menus;
    } else {
        // 没有定义菜单，从路由构建菜单，只获取有 title 字段的菜单
        menu.children = (p.routers || []).filter(v => v.title).map(v => {
            return {
                title: v.title,
                name: p.name + '-' + v.name
            };
        });
    }

    menus.push(menu);
    pagesRouters.push(router);
});

store.commit('SET_MENUS', menus);

const router = new VueRouter({
    routes: [{
        name: 'index',
        path: '/',
        title: '首页',
        component: layout,
    }]
});
router.addRoutes(pagesRouters);

export default router;
